/**   
 * @文件名称: ProductCategoriesAction.java
 * @类路径: com.lxj.cms.manage.action.categories
 * @描述: TODO
 * @公司：昆明天度网络信息科技有限公司
 * @作者：李兴建
 * @时间：2013-8-13 下午01:24:32
 * @版本：V1.0   
 */

package com.lxj.cms.manage.action.categories;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.lxj.cms.manage.action.ManageBaseAction;
import com.lxj.cms.manage.entity.ProductBrandsEntity;
import com.lxj.cms.manage.entity.ProductCategoriesEntity;
import com.lxj.core.action.IBaseAction;

/**
 * @类功能说明：
 * @类修改者：
 * @修改日期：
 * @修改说明：
 * @公司：昆明天度网络信息科技有限公司
 * @作者：李兴建
 * @创建时间：2013-8-13 下午01:24:32
 * @版本：V1.0
 */
@Results( { @Result(name = "index", location = "/WEB-INF/admin/categories/productCategories.jsp"), @Result(name = "modifyOrCreate", location = "/WEB-INF/business/newsinfo/classTypeAdd.jsp") })
public class ProductCategoriesAction extends ManageBaseAction implements IBaseAction {

	private static final long serialVersionUID = 6786797274951003349L;

	private String title;
	private String parent;

	private String categoriesId;

	private String names;
	private String description;

	private Long selectedId;

	@Override
	public void dataList() {
		Criteria criteria = this.createCriteria(ProductCategoriesEntity.class);
		criteria.addOrder(Order.desc("priority"));

		List<ProductCategoriesEntity> pcList = criteria.list();
		List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
		for (ProductCategoriesEntity pc : pcList) {
			if (null == pc.getParent()) {
				items.add(getMapObj(pc));
			}
		}
		String jsonString = JSONSerializer.toJSON(items).toString();
		this.wirteResponse(jsonString);
	}

	// 品牌信息列表
	@SuppressWarnings("unchecked")
	public void brandsDataList() {
		Criteria criteria = this.createCriteria(ProductBrandsEntity.class);
		if (StringUtils.isNotEmpty(categoriesId)) {
			try {
				ProductCategoriesEntity temp = this.getBaseService().findById(Long.parseLong(categoriesId), ProductCategoriesEntity.class);
				List<ProductCategoriesEntity> childs = this.getBaseService().findByProperty("parent.beanId", temp.getBeanId(), ProductCategoriesEntity.class);
				List<Long> ids = new ArrayList<Long>();
				if (null != childs && childs.size() > 0) {
					for (ProductCategoriesEntity child : childs) {
						ids.add(child.getBeanId());
					}
				}
				ids.add(temp.getBeanId());
				criteria.add(Restrictions.in("categorie.beanId", ids));
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}

		}

		int total = criteria.list().size();
		criteria = getResultCriteria(criteria);

		List<ProductBrandsEntity> criteriaList = criteria.list();
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
		for (ProductBrandsEntity entity : criteriaList) {
			Map map = new HashMap<String, Object>();
			map.put("beanId", entity.getBeanId());
			map.put("categorie", entity.getCategorie().getInfoTitle());
			map.put("infoTitle", entity.getInfoTitle());
			mapList.add(map);
		}
		responseJson(total, mapList);

	}

	// 选中访问
	public void dataList2() {
		Criteria criteria = this.createCriteria(ProductCategoriesEntity.class);
		List<ProductCategoriesEntity> pcList = criteria.list();
		List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
		for (ProductCategoriesEntity pc : pcList) {
			if (null == pc.getParent()) {
				items.add(getMapObjSelect(pc));
			}
		}
		String jsonString = JSONSerializer.toJSON(items).toString();
		this.wirteResponse(jsonString);
	}

	private Map<String, Object> getMapObjSelect(ProductCategoriesEntity pc) {
		Map<String, Object> item = new HashMap<String, Object>();
		item.put("id", pc.getBeanId());
		item.put("text", pc.getInfoTitle());
		if (null != selectedId) {
			if (pc.getBeanId() == selectedId) {
				item.put("checked", true);
			}
		}
		List<Map<String, Object>> child = new ArrayList<Map<String, Object>>();
		if (null != pc.getChildren() && pc.getChildren().size() > 0) {
			for (ProductCategoriesEntity childTemp : pc.getChildren()) {
				Map<String, Object> childItem = new HashMap<String, Object>();
				childItem.put("id", childTemp.getBeanId());
				childItem.put("text", childTemp.getInfoTitle());
				// childItem.put("state", "closed");

				if (null != selectedId) {
					if (pc.getBeanId() == selectedId) {
						item.put("checked", true);
					}
				}

				child.add(childItem);
			}
			item.put("state", "closed");
			item.put("children", child);
		}
		return item;
	}

	private Map<String, Object> getMapObj(ProductCategoriesEntity pc) {
		Map<String, Object> item = new HashMap<String, Object>();
		item.put("id", pc.getBeanId());
		item.put("text", pc.getInfoTitle());
		List<Map<String, Object>> child = new ArrayList<Map<String, Object>>();
		if (null != pc.getChildren() && pc.getChildren().size() > 0) {
			for (ProductCategoriesEntity childTemp : pc.getChildren()) {
				Map<String, Object> childItem = new HashMap<String, Object>();
				childItem.put("id", childTemp.getBeanId());
				childItem.put("text", childTemp.getInfoTitle());
				// childItem.put("state", "closed");
				child.add(childItem);
			}
			item.put("state", "closed");
			item.put("children", child);
		}
		return item;
	}

	@Override
	public String editPage() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getCategoriesId() {
		return categoriesId;
	}

	public void setCategoriesId(String categoriesId) {
		this.categoriesId = categoriesId;
	}

	@Override
	public String index() {
		// TODO Auto-generated method stub
		return "index";
	}

	@Override
	public String preservation() {
		Map<Object, Object> map = new HashMap<Object, Object>();
		try {
			if (this.getBaseService().findByProperty("infoTitle", this.getTitle(), ProductCategoriesEntity.class).size() > 0) {
				map.put("failure", true);
				map.put("msg", "该名称已存在");
			} else {
				ProductCategoriesEntity root = null;
				if (StringUtils.isNotEmpty(this.getParent())) {
					try {
						Long id = Long.parseLong(this.getParent());
						root = this.getBaseService().findById(id, ProductCategoriesEntity.class);
					} catch (NumberFormatException e) {
						e.printStackTrace();
					}
				}
				ProductCategoriesEntity child = new ProductCategoriesEntity();
				child.setInfoTitle(this.getTitle());
				child.setDescription(this.getDescription());
				if (null != root) {
					child.setParent(root);
					this.getBaseService().saveOrUpdate(child);
					root.addChild(child);
					this.getBaseService().saveOrUpdate(root);
				} else {
					this.getBaseService().saveOrUpdate(child);
				}
				map.put("success", true);
			}
		} catch (Exception e) {
			map.put("failure", true);
			map.put("msg", "保存失败，请重试");
			e.printStackTrace();
		}
		this.setResult(map);
		return null;
	}

	@Override
	public String remove() {
		Map<Object, Object> map = new HashMap<Object, Object>();
		try {
			if (StringUtils.isNotEmpty(this.names)) {
				String[] idsTemp = this.getNames().split(",");
				for (String str : idsTemp) {
					if (StringUtils.isEmpty(str)) {
						continue;
					}
					try {
						this.getBaseService().delete("infoTitle", str, ProductCategoriesEntity.class);
					} catch (Exception e) {
						e.printStackTrace();
						continue;
					}

				}
			}

			map.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("failure", true);
			map.put("msg", "删除失败，请重试");
		}
		this.setResult(map);
		return null;
	}

	public Long getSelectedId() {
		return selectedId;
	}

	public void setSelectedId(Long selectedId) {
		this.selectedId = selectedId;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getParent() {
		return parent;
	}

	public void setParent(String parent) {
		this.parent = parent;
	}

	public String getNames() {
		return names;
	}

	public void setNames(String names) {
		this.names = names;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

}

class DateJsonValueProcessor implements JsonValueProcessor {
	private String format = "yyyy-MM-dd";

	public DateJsonValueProcessor() {
	}

	public DateJsonValueProcessor(String format) {
		this.format = format;
	}

	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		String[] obj = {};
		if (value instanceof Date[]) {
			SimpleDateFormat sf = new SimpleDateFormat(format);
			Date[] dates = (Date[]) value;
			obj = new String[dates.length];
			for (int i = 0; i < dates.length; i++) {
				obj[i] = sf.format(dates[i]);
			}
		}
		return obj;
	}

	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
		if (value instanceof Date) {
			String str = new SimpleDateFormat(format).format((Date) value);
			return str;
		}
		return value.toString();
	}

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

}

/**
 * 将Bean中的Timestamp转换为json中的日期字符串
 */
class TimestampDateJsonValueProcessor implements JsonValueProcessor {
	public static final String Default_DATE_PATTERN = "yyyy-MM-dd";
	private DateFormat dateFormat;

	public TimestampDateJsonValueProcessor(String datePattern) {
		try {
			dateFormat = new SimpleDateFormat(datePattern);

		} catch (Exception e) {
			dateFormat = new SimpleDateFormat(Default_DATE_PATTERN);

		}

	}

	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		return process(value);
	}

	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
		return process(value);
	}

	private Object process(Object value) {
		return dateFormat.format((Date) value);

	}

	public DateFormat getDateFormat() {
		return dateFormat;
	}

	public void setDateFormat(DateFormat dateFormat) {
		this.dateFormat = dateFormat;
	}
}

class LongValueProcessor implements JsonValueProcessor {

	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		return process(value);
	}

	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
		return process(value);
	}

	private Object process(Object value) {

		return value.toString();
	}
}